import getopt,sys,json,redis
import datetime

env = "prod" 
delay_task_key = "delay_task_queue"

opts, args = getopt.getopt(sys.argv[1:], "","env=")
for opt, arg in opts:
    if opt == '--env':
        env = arg
        break

if env == "prod" :

    redis_host = "r-j6cmt5ayr2nq1m6zpp.redis.rds.aliyuncs.com"
    redis_db = 0
    redis_pwd = "r-j6cmt5ayr2nq1m6zpp:qpalmz1209@L"
else:
    redis_host = "192.168.1.4"
    redis_db = 0
    redis_pwd = "ubd83922c944c7e45b45ab5c86f98e7f"

def writeLog(data):
    now = datetime.datetime.now().strftime('%Y-%m-%d')
    path = "./logs/delay_{}.txt".format(now)
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    file = open(path,'a+')
    file.write(now+" "+data + '\n')
    file.close()

#redis
r = redis.StrictRedis(host=redis_host,port=6379, db=redis_db, password=redis_pwd)

# 每次处理的任务数
num = 0

while num < 20: 
    sdinput = r.lpop(delay_task_key)
    if sdinput == None:
        writeLog("no task!!")
        break
    
    toStr = str(sdinput,encoding="utf-8")
    writeLog("item: {}".format(toStr))
    arr = json.loads(toStr)
    if "queue_key" in arr :
        # 拿到实际执行任务的队列名称
        task_queue_key = arr["queue_key"]
        
        task = arr["task"]
        # 添加delay标识
        if "is_delay" not in task:
            task["is_delay"] = 1
        r.rpush(task_queue_key,json.dumps(task))
        writeLog("task_id : {} rpush {} queue".format(task["task_id"],task_queue_key))
        num += 1


